package com.wangwenjun.concurrency.chapter14.spindemo;

import java.util.concurrent.atomic.AtomicReference;

/**
 *  自己写一个自旋锁 控制并发
 */
public class SpinLock {
    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    private static int num = 0;

    public void lock(){
        while (!atomicReference.compareAndSet(null,Thread.currentThread())){
            //让线程自旋
        }
    }

    public void unlock(){
        atomicReference.compareAndSet(Thread.currentThread(),null);
    }

    public static void main(String[] args) throws Exception {
        SpinLock spinLock = new SpinLock();
        for(int i = 0;i < 100000;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    spinLock.lock();//这里拿不到锁会自旋
                    num++;
                    spinLock.unlock();
                }
            }).start();
        }

        Thread.sleep(3_000);

        System.out.println(num);


    }
}
